<script lang="ts" setup>
import * as THREE from 'three'
let SEPARATION = 100,
    AMOUNTX = 60,
    AMOUNTY = 60;
let container;
let camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer;
let particles: any[], particle, count = 0;
let mouseX = 100,
    mouseY = -170;
function init() {
  container = document.createElement('div');
  let tc = document.querySelector('.three-container') as HTMLElement
  tc.appendChild(container);
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.z = 1000;

  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xffffff);

  particles = new Array();

  var PI2 = Math.PI * 2;

  // 创建圆形纹理
  var circleTexture = new THREE.Texture(generateCircleTexture());
  circleTexture.needsUpdate = true;

  var material = new THREE.SpriteMaterial({
    color: 0x3389f7,
    map: circleTexture, // 使用圆形纹理
  });

  var i = 0;
  for (var ix = 0; ix < AMOUNTX; ix++) {
    for (var iy = 0; iy < AMOUNTY; iy++) {
      var particle = particles[i++] = new THREE.Sprite(material);
      particle.position.x = ix * SEPARATION - ((AMOUNTX * SEPARATION) / 2);
      particle.position.z = iy * SEPARATION - ((AMOUNTY * SEPARATION) / 2);
      scene.add(particle);
    }
  }

  renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  window.addEventListener('resize', onWindowResize, false);
}

function generateCircleTexture() {
  let canvas = document.createElement('canvas');
  canvas.width = 32;
  canvas.height = 32;
  let context = canvas.getContext('2d') as  CanvasRenderingContext2D;
  context.beginPath();
  context.arc(16, 16, 15, 0, Math.PI * 2, true);
  context.closePath();
  context.fillStyle = 'white';
  context.fill();
  return canvas;
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {
  camera.position.x += (mouseX - camera.position.x) * .05;
  camera.position.y += (-mouseY - camera.position.y) * .05;
  camera.lookAt(scene.position);

  var i = 0;
  for (var ix = 0; ix < AMOUNTX; ix++) {
    for (var iy = 0; iy < AMOUNTY; iy++) {
      particle = particles[i++];
      particle.position.y = (Math.sin((ix + count) * 0.3) * 50) + (Math.sin((iy + count) * 0.5) * 50);
      particle.scale.x = particle.scale.y = (Math.sin((ix + count) * 0.3) + 1) * 2 + (Math.sin((iy +
          count) * 0.5) + 1) * 2;
    }
  }
  renderer.render(scene, camera);
  count += 0.1;
}
onMounted(()=>{
  init();
  animate();
})
onUnmounted(()=>{
  window.removeEventListener('resize', onWindowResize, false);

})
</script>

<template>
<div class="three-container"></div>
</template>

<style scoped lang="scss">

</style>
